package net.wofly.right.service.impl;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import net.wofly.common.condition.Condition;
import net.wofly.common.condition.ConditionRelate;
import net.wofly.common.condition.ConditionUtil;
import net.wofly.common.condition.FilterCondition;
import net.wofly.common.condition.Operation;
import net.wofly.common.json.XiNiaoJSON;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.CryptUserUtil;
import net.wofly.common.util.Identities;
import net.wofly.common.util.PageHelper;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import net.wofly.right.domain.Customer;
import net.wofly.right.domain.Organization;
import net.wofly.right.domain.Role;
import net.wofly.right.domain.User;
import net.wofly.right.domain.UserRole;
import net.wofly.right.service.ICustomerService;
import net.wofly.right.service.IOrganizationService;
import net.wofly.right.service.IRegisterVerifyInfoService;
import net.wofly.right.service.IRightService;
import net.wofly.right.service.IRoleService;
import net.wofly.right.service.IUserRoleService;
import net.wofly.right.service.IUserService;
import net.wofly.right.shiro.LoginType;
import net.wofly.right.shiro.MyUsernamePasswordToken;
import net.wofly.right.util.UserType;
import net.wofly.right.util.VerifyCodeCheck;
import net.wofly.sale.exchange.domain.ExchangeStock;
import net.wofly.sale.exchange.service.IExchangeStockService;
import net.wofly.sale.stock.domain.Warehouse;
import net.wofly.sale.stock.service.IWarehouseService;
import net.wofly.sale.stock.util.WarehouseType;

/**
 * Created by LiuJianbo on 2017/9/22.
 */
@Service("iRightService")
@Transactional
public class RightServiceImpl implements IRightService {
    
    private static final String EMPLOYEE_WAREHOUSE_NAME_SUFFIX = "的仓库";
    private static final String ORGANIZATION_WAREHOUSE_NAME_SUFFIX = "的仓库";
    
    @Autowired
    IUserService iUserService;
    @Autowired
    IUserRoleService iUserRoleService;
    @Autowired
    IOrganizationService iOrganizationService;
    @Autowired
    IWarehouseService iWarehouseService;
    @Autowired
    IRoleService iRoleService;
    @Autowired
    IExchangeStockService iExchangeStockService;
    @Autowired
    IRegisterVerifyInfoService iRegisterVerifyInfoService;
    @Autowired
    ICustomerService iCustomerService;

    @Override
    public ReturnBean<User> addUser(User user) {
        //不判断该员工已经注册为公共会员了 ，因为员工也可以是会员， 登录入口不一样
        List<User> byMobiles = iUserService.findByMobile(user.getMobile());
        if (byMobiles != null && byMobiles.size()>0) {
            return new ReturnBean<User>(ResultCode.ERROR_SERVICE, "该雇员已经存在");
        }
        Organization organization = iOrganizationService.findOne(user.getOrganizationID());
        if (organization == null) {
            return new ReturnBean<User>(ResultCode.ERROR_SERVICE, "该雇员的组织机构不存在");
        }
        user.setUserID(Identities.uuid2());
        user.setStatus(1);
        //添加的用户法人属性都是0
        user.setIsLegal(0);
        //0: 内部员工
        user.setUserType(UserType.内部员工.getValue());
        user.setModifyDate(System.currentTimeMillis());
        String realPassword = user.getPassword();//TODO 需要解密
        user.setPassword(CryptUserUtil.generatePassword(realPassword));
        if (user.getWarehouseFlag().intValue() == 1) {
            createWareHouse(user.getUserID(), WarehouseType.个人仓库, user.getName() + EMPLOYEE_WAREHOUSE_NAME_SUFFIX);
            user.setWarehouseType(WarehouseType.个人仓库.getValue());
        }
        return new ReturnBean<User>(ResultCode.SUCCESS, "雇员添加成功", iUserService.save(user));
    }
    
    @Override
    public ReturnBean<Organization> addOrganization(Organization organization) {
        String organizationID = Identities.uuid2();
        organization.setOrganizationID(Identities.uuid2());
        if (organization.getWarehouseFlag().intValue() == 1) {
            createWareHouse(organizationID, WarehouseType.部门仓库, organization.getOrganizationName() +
                    ORGANIZATION_WAREHOUSE_NAME_SUFFIX);
        }
        return new ReturnBean<Organization>(ResultCode.SUCCESS, "组织机构添加成功", iOrganizationService.save(organization));
    }
    
    private String createWareHouse(String warehouseID, WarehouseType warehouseType, String warehouseName) {
        Warehouse warehouse = new Warehouse();
        warehouse.setWarehouseID(warehouseID);
        warehouse.setStatus(1);
        // 仓库名称如何设置
        warehouse.setWarehouseName(warehouseName);
        warehouse.setWarehouseType(warehouseType.getValue().toString());
        warehouse.setModifyDate(System.currentTimeMillis());
        iWarehouseService.save(warehouse);
        return warehouseID;
    }
    
    @Override
    public ReturnBean<User> delUser(String userID) {
        User user = iUserService.findOne(userID);
        if (null == user) {
            return new ReturnBean<User>(ResultCode.ERROR_SERVICE, "该员工不存在");
        }
        //将员工置位无效
        user.setStatus(0);
        user.setModifyDate(System.currentTimeMillis());
        iUserService.delete(userID);
        return new ReturnBean<User>(ResultCode.SUCCESS, "员工删除成功", user);
    }
    
    @Override
    public ReturnBean<String> delOrganization(String organizationID) {
        
        Organization organization = iOrganizationService.findOne(organizationID);
        if (null == organization) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "该机构不存在");
        }
        organization.setStatus(0);
        organization.setModifyDate(System.currentTimeMillis());
        if (organization.getWarehouseFlag().intValue() == 1 && StringUtils.isEmpty(organization.getWarehouseID())) {
            Warehouse warehouse = iWarehouseService.findOne(organization.getWarehouseID());
            if (warehouse != null) {
                warehouse.setStatus(0);
                warehouse.setModifyDate(System.currentTimeMillis());
                iWarehouseService.save(warehouse);
            }
        }
        
        
        
        iOrganizationService.save(organization);
        return new ReturnBean<String>(ResultCode.SUCCESS, "组织机构删除成功");
    }
    
    @Override
    public ReturnBean<PageWrapper<User>> getAllUser(Integer flag, Integer pageNum, Integer pageSize) {
        Condition condition = new Condition();
        List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
        filterConditions.add(new FilterCondition(String.valueOf(flag), "status", ConditionRelate.and.name(),
                Operation.eq.name(), 1));
        condition.setFilterCondition(filterConditions);
        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), User.class).getResult();
        
        Pageable pageable = new PageRequest(pageNum - 1, pageSize);
        Page<User> page = iUserService.findAll(condition.getSpecification(), pageable);
        
        return new ReturnBean<PageWrapper<User>>(ResultCode.SUCCESS, "查询成功", PageHelper.toPage(page));
    }
    
    @Override
    public ReturnBean<List<Organization>> getAllOrganization(Integer flag) {
        List<Organization> organizationList;
        //查询所有员工
        if (flag.intValue() == -1) {
            organizationList = iOrganizationService.findAll();
        } else {
            organizationList = iOrganizationService.findByStatus(flag);
        }
        return new ReturnBean<List<Organization>>(ResultCode.SUCCESS, "查询成功", organizationList);
    }
    
    @Override
    public ReturnBean<List<User>> getUserByOrganization(String organizationID, Integer flag) {
        //   是否需要分页  暂时不用分页
        List<User> userList;
        if (flag.intValue() == -1) {
            userList = iUserService.findByOrganizationID(organizationID);
        } else {
            userList = iUserService.findByOrganizationIDAndStatus(organizationID, 1);
        }
        return new ReturnBean<List<User>>(ResultCode.SUCCESS, "查询成功", userList);
    }
    
    @Override
    public ReturnBean<List<User>> getUserByRole(String roleID) {
        List<User> userList = null;
        Role role = iRoleService.findOne(roleID);
        if (role == null) {
            return new ReturnBean<List<User>>(ResultCode.ERROR_SERVICE, "角色不存在");
        }
        userList = iUserRoleService.findUsersByRoleID(roleID);
        return new ReturnBean<List<User>>(ResultCode.SUCCESS, "查询成功", userList);
    }
    
    @Override
    public ReturnBean<List<User>> getBussManagerAndClerk() {
        List<String> roleList = new ArrayList<String>();
        roleList.add("106") ;
        roleList.add("105") ;
        
        List<User> userList = iUserRoleService.findUsersByRoleIDs(roleList) ;
        return new ReturnBean<List<User>>(ResultCode.SUCCESS, "查询成功", userList);
    }
    
    @Override
    public ReturnBean<List<Role>> getUserRole(String userID) {
        List<Role> roleList;
        User user = iUserService.findOne(userID);
        if (null == user) {
            return new ReturnBean<List<Role>>(ResultCode.ERROR_SERVICE, "员工不存在");
        }
        roleList = iUserRoleService.findRolesByUserID(userID);
        return new ReturnBean<List<Role>>(ResultCode.SUCCESS, "查询成功", roleList);
    }
    
    @Override
    public ReturnBean<String> setUserRole(UserRole userRole) {
        User seter = iUserService.findOne(userRole.getSetUserID());
        if (null == seter) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "员工(操作者)不存在");
        }
        User user = iUserService.findOne(userRole.getUserID());
        if (null == user) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "员工不存在");
        }
        Role role = iRoleService.findOne(userRole.getRoleID());
        if (role == null) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "角色不存在");
        }
        if (StringUtils.isEmpty(userRole.getUserRoleID())) {
            userRole.setUserRoleID(Identities.uuid2());
        }
        long modifyDate = System.currentTimeMillis();
        //初始化库存
        if (role.getExchangeFlag().intValue() == 1) {
            ExchangeStock exchangeStock = iExchangeStockService.findOne(userRole.getUserID());
            if (exchangeStock == null) {
                ExchangeStock exchangeStock1 = new ExchangeStock();
                exchangeStock1.setExchangeStockID(userRole.getUserID());
                exchangeStock1.setNum(0);
                exchangeStock1.setModifyDate(modifyDate);
                iExchangeStockService.save(exchangeStock1);
            }
        }
        
        userRole.setModifyDate(modifyDate);
        iUserRoleService.save(userRole);
        return new ReturnBean<String>(ResultCode.SUCCESS, "修改成功");
    }
    
    @Override
    public ReturnBean<User> updateUser(User user) {
        User dbUser = iUserService.findOne(user.getUserID());
        user.setModifyDate(System.currentTimeMillis());
        //  修改密码是有单独的接口
        user.setPassword(dbUser.getPassword());
        return new ReturnBean<User>(ResultCode.SUCCESS, "修改成功", iUserService.save(user));
    }
    
    @Override
    public ReturnBean<Organization> updateOrganization(Organization organization) {
        Organization dbOrganization = iOrganizationService.findOne(organization.getOrganizationID());
        if (null == dbOrganization) {
            return new ReturnBean<Organization>(ResultCode.ERROR_SERVICE, "机构不存在或者传入的值不正确");
        }
        if (dbOrganization.getWarehouseFlag().intValue() == 0 && StringUtils.isEmpty(dbOrganization.getWarehouseID())) {
            createWareHouse(organization.getOrganizationID(), WarehouseType.部门仓库, organization.getOrganizationName() +
                    ORGANIZATION_WAREHOUSE_NAME_SUFFIX);
        }
        if (dbOrganization.getWarehouseFlag().intValue() == 1 && !StringUtils.isEmpty(
                dbOrganization.getWarehouseID()) && organization.getWarehouseFlag().intValue() == 0) {
            return new ReturnBean<Organization>(ResultCode.ERROR_SERVICE, "该机构已经存在仓库，不可以将是否有仓库修改为无仓库状态");
        }
        organization.setModifyDate(System.currentTimeMillis());
        return new ReturnBean<Organization>(ResultCode.SUCCESS, "修改成功", iOrganizationService.save(organization));
    }
    
    @Override
    public ReturnBean<String> login(String mobile, String password) {
        try {
            Subject subject = SecurityUtils.getSubject();
            MyUsernamePasswordToken usernamePasswordToken = new MyUsernamePasswordToken(mobile, password,
                    LoginType.EMPLOYEE);
            subject.login(usernamePasswordToken);
            return new ReturnBean<String>(ResultCode.SUCCESS, "登录成功");
            
        } catch (Exception e) {
            return new ReturnBean<String>(ResultCode.ERROR_SERVICE, "登录失败，账号或密码不正确");
        }
    }

    @Override
    public ReturnBean<String> changeMobile(String userID, String pwd, String newMobile, String verifyCode) {

        User user = iUserService.findOne(userID);
        if (null == user) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户不存在!");
        }

        if (!CryptUserUtil.generatePassword(pwd).equals(user.getPassword())) {
            return new ReturnBean<>(-2, "旧密码不正确!");
        }

        List<User> newMobileUsers = iUserService.findByMobile(newMobile);
        if (null != newMobileUsers && newMobileUsers.size()>0) {
            return new ReturnBean<>(-3, "手机号已被使用!");
        }

        ReturnBean<String> verifyCodeResult = VerifyCodeCheck.verifyCodeCheck(iRegisterVerifyInfoService, newMobile, verifyCode);
        if (verifyCodeResult.getCode() != ResultCode.SUCCESS.intValue()) {
            return verifyCodeResult;
        }

        user.setMobile(newMobile);
        iUserService.save(user);
        return new ReturnBean<>(ResultCode.SUCCESS, "修改手机号成功!");
    }

    @Override
    public ReturnBean<String> findPwdByMobile(String mobile, String verifyCode, String newPwd) {
        List<User> users = iUserService.findByMobile(mobile);
        if (null == users && users.size()<=0) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户不存在!");
        }

        ReturnBean<String> verifyCodeResult = VerifyCodeCheck.verifyCodeCheck(iRegisterVerifyInfoService, mobile, verifyCode);
        if (verifyCodeResult.getCode() != ResultCode.SUCCESS.intValue()) {
            return verifyCodeResult;
        }
        
        User user = users.get(0) ;

        user.setPassword(CryptUserUtil.generatePassword(newPwd));
        iUserService.save(user);
        return new ReturnBean<>(ResultCode.SUCCESS, "通过手机，找回密码成功!");
    }

    @Override
    public ReturnBean<User> getUser(String userID) {
        User user = iUserService.findOne(userID);
        return new ReturnBean<>(ResultCode.SUCCESS, "获取用户信息成功！", user);
    }

    @Override
    public ReturnBean<String> modifyPwd(String userID, String oldPwd, String newPwd) {
        User user = iUserService.findOne(userID);
        if (null == user) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户不存在!");
        }

        if (!CryptUserUtil.generatePassword(oldPwd).equals(user.getPassword())) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "旧密码不正确!");
        }

        user.setPassword(CryptUserUtil.generatePassword(newPwd));
        iUserService.save(user);
        return new ReturnBean<>(ResultCode.SUCCESS, "修改密码成功！");
    }

    @Override
    public ReturnBean<String> setUserNickName(String userID, String nickName, Integer sex) {
        User user = iUserService.findOne(userID);
        if (null == user) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户不存在!");
        }

        user.setName(nickName);
        user.setSex(sex);
        iUserService.save(user);
        return new ReturnBean<>(ResultCode.SUCCESS, "设置用户昵称与性别成功！");
    }

    @Override
    public ReturnBean<String> uploadUserHeadPic(String userID, MultipartFile headPic, String path) {
        User user = iUserService.findOne(userID);
        if (null == user) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户不存在!");
        }
        LocalDate today = LocalDate.now();
        String targetPath = File.separator+"static"+File.separator+"images"+File.separator+"headPic" + File.separator + today.getYear() + File.separator + today.getMonthValue();
        String fileName = Identities.uuid2() + "." +headPic.getOriginalFilename().split("\\.")[1];
        String relativePath = targetPath + File.separator + fileName;
        String $file = path + relativePath;
        File uploadedFile = new File($file);
        if(uploadedFile == null){
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "targetFile is not be null");
        }
        File f= new File(uploadedFile.getParent());
        if(!f.exists()){
            f.mkdirs();
        }

        try {
            FileCopyUtils.copy(headPic.getBytes(), uploadedFile);
        } catch (IOException e) {
            e.printStackTrace();
            return new ReturnBean<>(ResultCode.ERROR_SERVICE,"上传用户头像出错！");
        }

        user.setPic1(relativePath);
        user.setPic2(relativePath);

        iUserService.save(user);
        return new ReturnBean<>(ResultCode.SUCCESS, "上传用户头像成功！", relativePath);
    }
    
    @Override
    public ReturnBean<List<Organization>> getAllShop() {
        // 查询有仓库的机构，只有公司和门店有仓库 , 去除公司
        List<Organization> organizationList = iOrganizationService.findByOrganizationCodeStartingWithAndOrganizationCodeNot("100100400");
        return new ReturnBean<List<Organization>>(ResultCode.SUCCESS, "", organizationList);
    }

	@Override
	public ReturnBean<Customer> delCustomer(String customerID) {
		
		Organization organization = iOrganizationService.findOne(customerID);
        if (null == organization) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "该机构不存在");
        }
        organization.setStatus(0);
        organization.setModifyDate(System.currentTimeMillis());
        if (organization.getWarehouseFlag().intValue() == 1 && StringUtils.isEmpty(organization.getWarehouseID())) {
            Warehouse warehouse = iWarehouseService.findOne(organization.getWarehouseID());
            if (warehouse != null) {
                warehouse.setStatus(0);
                warehouse.setModifyDate(System.currentTimeMillis());
                iWarehouseService.save(warehouse);
            }
        }
        
        iOrganizationService.save(organization);
        
        List<User> users = iUserService.findByOrganizationID(customerID) ;
        if (null != users && !users.isEmpty()) {
        		for(User user :users) {
        			user.setStatus(0);
        			user.setModifyDate(System.currentTimeMillis());
        		}
        		iUserService.save(users) ;
        }
        
        iCustomerService.findOne(customerID) ;
		
        return new ReturnBean<>(ResultCode.SUCCESS, "删除客户成功！",iCustomerService.findOne(customerID));
	}

	@Override
	public ReturnBean<Customer> recoverCustomer(String customerID) {
		Organization organization = iOrganizationService.findOne(customerID);
        if (null == organization) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "该机构不存在");
        }
        organization.setStatus(1);
        organization.setModifyDate(System.currentTimeMillis());
        if (organization.getWarehouseFlag().intValue() == 1 && StringUtils.isEmpty(organization.getWarehouseID())) {
            Warehouse warehouse = iWarehouseService.findOne(organization.getWarehouseID());
            if (warehouse != null) {
                warehouse.setStatus(1);
                warehouse.setModifyDate(System.currentTimeMillis());
                iWarehouseService.save(warehouse);
            }
        }
        
        iOrganizationService.save(organization);
        
        User user= iUserService.findOne(customerID) ;
        if (null != user) {
        		user.setStatus(1);
        		user.setModifyDate(System.currentTimeMillis());
        		iUserService.save(user) ;
        }
		
        return new ReturnBean<>(ResultCode.SUCCESS, "客户恢复成功！",iCustomerService.findOne(customerID));
	}
}
